<template>
  <div class="search-fullscreen">
    <!-- 搜索头部 -->
    <div class="search-header">
      <van-icon
          class="search-back"
          name="arrow-left"
          @click="handleBack"
      />
      <div class="search-input-container">
        <van-search
            v-model="searchValue"
            placeholder="搜索商品、品牌、分类"
            shape="round"
            autofocus
            @search="handleSearch"
        />
        <!-- 新增：搜索按钮 -->
        <van-button
            type="primary"
            size="small"
            class="search-button"
            @click="handleSearch"
            color="white"
        >
         <p style="color: #78b11d;font-size: 18px">搜索</p>
        </van-button>
      </div>
    </div>

    <!-- 条件渲染：显示搜索界面或搜索结果 -->
    <div v-if="!showResult" class="search-body">
      <!-- 搜索历史 -->
      <div class="search-history" v-if="searchHistory.length > 0">
        <h3 class="section-title">
          搜索历史
          <span class="clear-history" @click="clearSearchHistory">
            <van-icon name="delete" color="red" />
          </span>
        </h3>
        <div class="history-tags">
          <van-tag
              v-for="(item, index) in searchHistory"
              :key="index"
              plain
              type="primary"
              size="medium"
              class="history-tag"
              @click="searchFromHistory(item)"
          >
            {{ item }}
          </van-tag>
        </div>
      </div>

      <!-- 热门搜索 -->
      <div class="search-hot">
        <h3 class="section-title">热门搜索</h3>
        <div class="hot-list">
          <div
              v-for="(item, index) in hotSearch"
              :key="item.id"
              class="hot-item"
              @click="searchFromHot(item.name)"
          >
            <div class="hot-rank" :class="{ top3: index < 3 }">
              {{ index + 1 }}
            </div>
            <div class="hot-info">
              <div class="hot-name">{{ item.name }}</div>
              <div class="hot-desc">{{ item.desc }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索结果区域 - 直接嵌入Result组件 -->
    <div v-else class="search-result-container">
      <Result :keyword="currentKeyword" @back="showResult = false" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import Result from './Result.vue' // 引入Result组件

const router = useRouter()
const route = useRoute()
const searchValue = ref('')
const searchHistory = ref([])
const showResult = ref(false) // 控制是否显示结果
const currentKeyword = ref('') // 当前搜索关键词

const hotSearch = ref([
  { id: 1, name: '鸡子', desc: '3245人搜索' },
  { id: 2, name: '蛋白粉', desc: '2987人搜索' },
  { id: 3, name: '运动装备', desc: '2564人搜索' },
  { id: 4, name: '夏季新品', desc: '2134人搜索' },
  { id: 5, name: '家用电器', desc: '1987人搜索' },
  { id: 6, name: '美妆护肤', desc: '1765人搜索' }
])

// 加载搜索历史
onMounted(() => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }

  // 检查路由参数，如果有keyword则直接显示结果
  if (route.query.keyword) {
    const keyword = route.query.keyword.toString()
    searchValue.value = keyword
    currentKeyword.value = keyword
    showResult.value = true
    addToSearchHistory(keyword)
  }
})

// 返回上一页
const handleBack = () => {
  if (showResult.value) {
    showResult.value = false
  } else {
    router.back()
  }
}

// 执行搜索
const handleSearch = () => {
  const searchTerm =searchValue.value
  if (!searchTerm||!searchTerm.trim()) {
    showToast('请输入搜索内容')
    return
  }

  // 添加到搜索历史
  addToSearchHistory(searchTerm)

  // 设置当前关键词
  currentKeyword.value = searchTerm

  // 关键修改：先隐藏结果再显示，强制重新挂载组件
  showResult.value = false

  // 使用nextTick确保DOM更新后再显示结果
  setTimeout(() => {
    showResult.value = true
  }, 0)
}

// 添加到搜索历史
const addToSearchHistory = (term) => {
  // 移除已存在的相同项
  const filteredHistory = searchHistory.value.filter(item => item !== term)

  // 添加到开头
  filteredHistory.unshift(term)

  // 限制历史记录数量
  if (filteredHistory.length > 10) {
    filteredHistory.length = 10
  }

  searchHistory.value = filteredHistory
  localStorage.setItem('searchHistory', JSON.stringify(filteredHistory))
}

// 从历史记录搜索
const searchFromHistory = (item) => {
  searchValue.value = item
  handleSearch(item)
}

// 从热门搜索
const searchFromHot = (name) => {
  searchValue.value = name
  handleSearch(name)
}

// 清空搜索历史
const clearSearchHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
  showToast('搜索历史已清空')
}
</script>

<style scoped>
.search-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.search-back {
  margin-right: 12px;
  font-size: 20px;
  cursor: pointer;
}

.search-input-container {
  flex: 1;
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 8px; /* 搜索框与按钮之间的间距 */
}
.search-input-container :deep(.van-search) {
  flex: 1;
}
.search-button {
  /* 你可以根据需要调整按钮的样式，例如固定宽度 */
  white-space: nowrap;
}

.search-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  -webkit-overflow-scrolling: touch;
}

.search-history {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.clear-history {
  font-size: 14px;
  color: white;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  margin-bottom: 8px;
}

.hot-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.hot-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.hot-rank {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 4px;
  margin-right: 12px;
  font-size: 12px;
}

.hot-rank.top3 {
  background: #ff6b6b;
  color: white;
}

.hot-info {
  flex: 1;
}

.hot-name {
  font-size: 14px;
  color: #323233;
  margin-bottom: 4px;
}

.hot-desc {
  font-size: 12px;
  color: #999;
}

.search-result-container {
  flex: 1;
  overflow-y: auto;
}
</style>